import axios, { AxiosInstance, AxiosError, InternalAxiosRequestConfig, AxiosResponse, AxiosRequestConfig } from 'axios';
import { api } from '@T2/plugins/env-config';
import { ElMessage } from 'element-plus';
import { useIuserInfoStore, useCurrentWatchStore } from '@T2/store/users.ts';
import Cookies from 'js-cookie';

const axiosInstance: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_URL,
  timeout: 10000,
});
    
/* 请求拦截器 */
axiosInstance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    //在发送请求之前做什么
    const c = Cookies.get('csrftoken');
    if (c) {
      config.headers['X-CSRFToken'] = Cookies.get('csrftoken');
    }
    if (config?.url?.includes('/ruoshui/common/rest/file/') && config.method == 'post') {
      config.headers['Content-Type'] = 'multipart/form-data';//这里为什么要用form-data呢？？？？？？
    }
    return config;
  },
  (error) =>
  // 对请求错误做些什么
  Promise.reject(error)
);
/* 响应拦截器 */
axiosInstance.interceptors.response.use(
  (response: AxiosResponse) => {
    // hideLoading(response.config);
    //响应成功
    return response.data;
  },
  (error: AxiosError) => {
    if (error?.response?.status == 400) {
      let data = JSON.stringify(error.response.data);
      let i = data.indexOf(':');
      let a = data.substring(i + 2, data.length - 2);
      ElMessage.error(a);
      return Promise.reject(error);
    }
    if (error?.response?.status == 403) {
      ElMessage.error('登录过期，请重新登录');
      setTimeout(() => {
        location.href = "/";
      }, 500);
      return Promise.reject(error);
    } else if (error?.response?.status) {
      const status = error.response.status;
      let message = "";
      switch (status) {
        case 401:
          message = '请求错误';
          break;
        case 404:
          message = '请求地址出错';
          break;
        case 408:
          message = '请求超时';
          break;
        case 500:
          message = '服务器内部错误!';
          break;
        case 501:
          message = '服务未实现!';
          break;
        case 502:
          message = '网关错误!';
          break;
        case 503:
          message = '服务不可用!';
          break;
        case 504:
          message = '网关超时!';
          break;
        default:
          message = '请求失败'
      }
      ElMessage.error(message);
      return Promise.reject(error);
    }
    return Promise.reject(error);
  }
);

type Expand<T> = T extends infer O ? { [K in keyof O]: O[K] } : never;
export type payload = Expand<{
  method: 'get' | 'post' | 'patch' | 'delete' | 'put',
  id?: number,
  params?: {
    noProject?: boolean,
    noCompany?: boolean,
    [propName: string]: any,
  },
  data?: {
    noProject?: boolean,
    noCompany?: boolean,
    [propName: string]: any,
  },
  config?: AxiosRequestConfig<any>,
}>
const AxiosDIY = (payload: payload, url: string) => {
  url = api + url;
  if (payload.method === 'post') {
    return axiosInstance.post(url, payload.data, {
      ...payload.config,
    })
  } else if (payload.method === 'patch') {
    return axiosInstance.patch(url, payload.data, {
      ...payload.config,
    })
  } else if (payload.method === 'put') {
    return axiosInstance.put(url, payload.data, {
      ...payload.config,
    })
  } else if (payload.method === 'delete') {
    return axiosInstance.delete(url, {
      ...payload.config,
      data: payload.data,
    })
  } else {
    let obj: any = {
      ordering: '-create_time',
      ...payload.params,
    };
    const iuserInfoStore = useIuserInfoStore();
    const { info } = iuserInfoStore;
    const currentWatchStore = useCurrentWatchStore();
    const { level, curProject } = currentWatchStore;
    if (obj.noProject) {
      delete obj.noProject;
    } else if (level === 'project') {
      obj.project = curProject.id;
    }
    if (obj.noCompany) {
      delete obj.noCompany;
    } else {
      obj.company = info.company;
    }
    return axiosInstance.get(url, {
      ...payload.config,
      params: obj,
    })
  }
}

export default AxiosDIY;